package com.pw.canbuslogger.view;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.lang.Script;

import java.awt.BorderLayout;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JTextArea;
import javax.swing.JTable;
import javax.swing.JToolBar;

import java.awt.Component;

import javax.swing.Box;

import com.pw.canbuslogger.CANBusRecordFields;
import com.pw.canbuslogger.view.grid.CANBusDatasetTableModel;
import com.pw.canbuslogger.view.grid.CANBusGridTableCellRender;
import com.pw.canbuslogger.view.grid.ICANBusRecordProcessor;

import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Enumeration;

import javax.swing.JToggleButton;
import javax.swing.table.TableColumn;
import javax.swing.JEditorPane;

import org.apache.commons.lang.StringUtils;

public class CANBusGridViewPanel extends JPanel implements ICANBusRecordProcessor {

    private static final Font ARIAL = new Font("Arial", Font.PLAIN, 10);
    private final JTable table;
    private final JTable jTableLog;
    private final CANBusDatasetTableModel model;
    private JToggleButton btnAtivarFiltro;
    private JTextArea jTextFiltro;
    public Binding groovyBinding;
    public Script groovyScript;

    /**
     * Create the panel.
     */
    public CANBusGridViewPanel() {
        setLayout(new BorderLayout(0, 0));
        this.setFont(ARIAL);

        JSplitPane topSplitPane = new JSplitPane();
        topSplitPane.setMinimumSize(new Dimension(244, 200));
        //add(topSplitPane, BorderLayout.NORTH);

        JPanel jPanelSendCommand = new JPanel();
        jPanelSendCommand.setBorder(BorderFactory.createTitledBorder("Comandos..."));
        topSplitPane.setLeftComponent(jPanelSendCommand);

        JToolBar tBarComandos = new JToolBar();
        tBarComandos.setFloatable(false);

        JScrollPane jScrollComandos = new JScrollPane();

        GroupLayout gl_jPanelSendCommand = new GroupLayout(jPanelSendCommand);
        gl_jPanelSendCommand.setHorizontalGroup(gl_jPanelSendCommand.createParallelGroup(Alignment.TRAILING).addGroup(Alignment.LEADING, gl_jPanelSendCommand.createSequentialGroup().addGap(6).addGroup(gl_jPanelSendCommand.createParallelGroup(Alignment.LEADING).addComponent(tBarComandos, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 335, Short.MAX_VALUE).addComponent(jScrollComandos, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE)).addContainerGap()));
        gl_jPanelSendCommand.setVerticalGroup(gl_jPanelSendCommand.createParallelGroup(Alignment.LEADING).addGroup(gl_jPanelSendCommand.createSequentialGroup().addComponent(tBarComandos, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(jScrollComandos, GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE).addContainerGap()));

        table = new JTable();
        table.setFillsViewportHeight(true);
        jScrollComandos.setViewportView(table);

        JButton btnNovoComando = new JButton("Novo");
        btnNovoComando.setToolTipText("Novo Comando");
        tBarComandos.add(btnNovoComando);

        JLabel lblSelComando = new JLabel("Selecionar");
        tBarComandos.add(lblSelComando);

        JComboBox jComboComandos = new JComboBox();
        jComboComandos.setMinimumSize(new Dimension(150, 27));
        jComboComandos.setPreferredSize(new Dimension(100, 27));
        jComboComandos.setSize(new Dimension(100, 0));
        tBarComandos.add(jComboComandos);

        JButton btnSalvarComando = new JButton("Salvar");
        btnSalvarComando.setToolTipText("Salvar Comando");
        tBarComandos.add(btnSalvarComando);

        JButton btnEnviarComando = new JButton("Enviar");
        btnEnviarComando.setToolTipText("Enviar Comando");
        tBarComandos.add(btnEnviarComando);
        jPanelSendCommand.setLayout(gl_jPanelSendCommand);

        JPanel jPanelFiltros = new JPanel();
        jPanelFiltros.setBorder(BorderFactory.createTitledBorder("Filtros..."));
        topSplitPane.setRightComponent(jPanelFiltros);

        JScrollPane scrollPane = new JScrollPane();

        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        this.jTextFiltro = new JTextArea();
        scrollPane.setViewportView(jTextFiltro);

        GroupLayout gl_panel_1 = new GroupLayout(jPanelFiltros);
        gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1.createSequentialGroup().addContainerGap().addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1.createSequentialGroup().addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE).addContainerGap()).addGroup(gl_panel_1.createSequentialGroup().addComponent(toolBar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addGap(0)))));
        gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1.createSequentialGroup().addComponent(toolBar, GroupLayout.PREFERRED_SIZE, 31, GroupLayout.PREFERRED_SIZE).addPreferredGap(ComponentPlacement.RELATED).addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE).addContainerGap()));

        JButton button = new JButton("Novo");
        button.setToolTipText("Novo Comando");
        toolBar.add(button);

        JLabel label = new JLabel("Selecionar");
        toolBar.add(label);

        JComboBox comboBox = new JComboBox();
        comboBox.setSize(new Dimension(100, 0));
        comboBox.setPreferredSize(new Dimension(100, 27));
        comboBox.setMinimumSize(new Dimension(150, 27));
        toolBar.add(comboBox);

        JButton btnSalvarFiltro = new JButton("Salvar");
        btnSalvarFiltro.setToolTipText("Salvar Filtro");
        toolBar.add(btnSalvarFiltro);

        btnAtivarFiltro = new JToggleButton("Ativar");
        btnAtivarFiltro.setToolTipText("Ativar Filtro");
        btnAtivarFiltro.addItemListener(new BtnAplicatFiltroItemListener());
        toolBar.add(btnAtivarFiltro);
        jPanelFiltros.setLayout(gl_panel_1);

        JSplitPane centerSplitPane = new JSplitPane();
        centerSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
        add(centerSplitPane, BorderLayout.CENTER);

        JScrollPane jScollLogTable = new JScrollPane();
        jScollLogTable.setMinimumSize(new Dimension(23, 100));
        centerSplitPane.setBottomComponent(jScollLogTable);
        centerSplitPane.setTopComponent(topSplitPane);

        this.model = new CANBusDatasetTableModel();

        jTableLog = new JTable(model);
        jTableLog.setFillsViewportHeight(true);

        CANBusGridTableCellRender render = new CANBusGridTableCellRender();
        Enumeration<TableColumn> columns = jTableLog.getColumnModel().getColumns();
        while (columns.hasMoreElements()) {
            TableColumn column = columns.nextElement();
            column.setCellRenderer(render);
        }
        jScollLogTable.setViewportView(jTableLog);

    }

    @Override
    public void accept(Object[] record) {
        if (this.evaluate(record)) {
            this.model.addRecord(record);
        }

    }

    private boolean evaluate(Object[] record) {
        if (groovyScript != null) {
            this.groovyBinding.setVariable("ID", record[CANBusRecordFields.ID]);
            this.groovyBinding.setVariable("B1", record[CANBusRecordFields.BYTE01]);
            this.groovyBinding.setVariable("B2", record[CANBusRecordFields.BYTE02]);
            this.groovyBinding.setVariable("B3", record[CANBusRecordFields.BYTE03]);
            this.groovyBinding.setVariable("B4", record[CANBusRecordFields.BYTE04]);
            this.groovyBinding.setVariable("B5", record[CANBusRecordFields.BYTE05]);
            this.groovyBinding.setVariable("B6", record[CANBusRecordFields.BYTE06]);
            this.groovyBinding.setVariable("B7", record[CANBusRecordFields.BYTE07]);
            this.groovyBinding.setVariable("B8", record[CANBusRecordFields.BYTE08]);

            return (boolean) groovyScript.run();
        }
        return true;

    }

    private class BtnAplicatFiltroItemListener implements ItemListener {

        @Override
        public void itemStateChanged(ItemEvent evt) {
            if (evt.getStateChange() == ItemEvent.SELECTED) {
                String filter = jTextFiltro.getText();
                if (!StringUtils.isBlank(filter)) {
                    CANBusGridViewPanel.this.groovyBinding = new Binding();
                    GroovyShell shell = new GroovyShell(CANBusGridViewPanel.this.groovyBinding);
                    CANBusGridViewPanel.this.groovyScript = shell.parse(filter);
                }
            } else {
                CANBusGridViewPanel.this.groovyBinding = null;
                CANBusGridViewPanel.this.groovyScript = null;
            }
        }

    }
}
